package com.shiningstars.service;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;

import com.shiningstars.database.DatabaseHandler;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Utilities;
import com.shiningstars.php.WebHelper;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.valuebeans.Audit;

public class AuditService extends Service implements Constants, Config {

	int attempts = SERVICE_ATTEMPTS;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		try {
			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

			final WebHelper webHelper = new WebHelper();
			final DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());

			new Thread() {
				@Override
				public void run() {

					Looper.prepare();

					while (attempts > 0) {
						attempts--;
						while (true) {
							Audit audit = databaseHandler.getAudit();

							if (null != audit) {
								try {
									JSONObject json = webHelper.audit(audit, getApplicationContext());

									if (null != json && json.getBoolean(SUCCESS)) {
										databaseHandler.deleteAudit(audit.getId());
									}
								} catch (JSONException e) {
									Utilities.logError(getApplicationContext(), AuditService.class.getName(), e);
									break;
								} catch (IllegalStateException e) {
									Utilities.logError(getApplicationContext(), AuditService.class.getName(), e);
									break;
								} catch (IOException e) {
									break;
								}
							}

							break;
						}

						try {
							Thread.sleep(SERVICE_THREAD_SLEEP);
						} catch (InterruptedException e) {
							Utilities.logError(getApplicationContext(), AuditService.class.getName(), e);
							break;
						}
					}

					stopService(new Intent(getApplicationContext(), AuditService.class));

					Looper.loop();
					Looper.myLooper().quit();
				}
			}.start();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), AuditService.class.getName(), e);
		}

		return START_NOT_STICKY;
	}
}